package sk.hackcraft.multibox.util;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Random;

public class IdentifiedCachedMap<T> extends HashMap<Long, WeakReference<T>> {
	static private Random random = new Random();
	
	private static final long serialVersionUID = -3962943965367707978L;

	public synchronized long add(T object) {
		long key;
		do {
			key = random.nextLong();
		} while(containsKey(key));
		
		put(key, new WeakReference<T>(object));
		
		return key;
	}
	
	public synchronized T get(long key) {
		WeakReference<T> ref = super.get(key);
		if(ref == null)
			return null;
		T obj = ref.get();
		if(obj == null)
			remove(key);
		return obj;
	}
}
